<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Store Class
 */
class CI_Store {

	private $CI;
	private $raw_store = array();
	private $cached_store = array();

	/**
	 *  Costructor
	 *
	 * Grabs all Cache elements from DB
	 *
	 */
	public function __construct()
	{
		$this->CI =& get_instance();

		$query = $this->CI->db->get('store');

		foreach ($query->result_array() as $row)
		{
			$this->raw_store[$row['name']] = $row;
		}
	}

	// --------------------------------------------------------------------

	/**
	 *  Return a store
	 *
	 * Finds store by name, unserializes if needed
	 * Returns false if no store found
	 *
	 */
	function data($store, $key=null)
	{

		if(!isset($this->cached_store[$store])) {

			// No store found
			if(!isset($this->raw_store[$store])) {
				return false;
			}

			$this->cached_store[$store] = @unserialize($this->raw_store[$store]['data']);
		}

		// Return store
		if($key != null) {
			return $this->cached_store[$store][$key];
		}
		else {
			return $this->cached_store[$store];
		}

	}

	// --------------------------------------------------------------------

	/**
	 *  Reload a store
	 *
	 * Reruns query to reload store
	 *
	 */
	function reload($store=null)
	{
		if($store == null) {

			foreach(array_keys($this->raw_store) as $rs)
			{
				$this->reload($rs);
			}

			return true;
		}

		if(!isset($this->raw_store[$store])) {
			return false;
		}

		if($store == 'vars') {
			$r = $this->_vars();
		}
		else {

			$meta = @unserialize($this->raw_store[$store]['meta']);
			$query = $this->CI->db->query($meta['query']);
			$r = $query->result_array();

			if(isset($meta['key'])) {

				$result = $r;
				$r = array();
				$val = array_keys($result[0]);

				if(count($val) == 2) {
					$val = $val[0] == $meta['key'] ? $val : array_reverse($val);
				}
				else {
					$val = '';
				}

				foreach($result as $row) {

					if($val != '') {
						$r[$row[$val[0]]] = $row[$val[1]];
					}
					else {

						$key = $row[$meta['key']];
						unset($row[$meta['key']]);
						$r[$key] = $row;

					}
				}
			}
		}

		$this->cached_store = $r;
		$this->CI->db->update('store', array('data' => serialize($r)), array('name' => $store));
		return $r;
	}

	// --------------------------------------------------------------------

	/**
	 *  Return vars
	 *
	 * This function sucks I'll make something better for vars later
	 *
	 */
	function _vars()
	{

		return array(
			'index' => 'forum/index'
		);

	}


}
// END Store Class

/* End of file Store.php */
/* Location: ./system/libraries/Store.php */
